"""
---------------------------------------------------------------------
- File: service_logs.py
- Date: 2025/11/19
- Author: yangzhide
- Email: xxzjyzd@126.com
- Description: 相关日志业务逻辑
---------------------------------------------------------------------
"""

from sqlalchemy import func, String
from sqlalchemy.orm import selectinload  # 关键导入
from sqlmodel import select, or_, cast

from app.models.system import Logs
from app.schemas.system.logs import LogsCreate, LogsUpdate, LogsReadWithUserName
from .service_crud import CRUDBase


class ServiceLogs(CRUDBase[Logs, LogsCreate, LogsUpdate]):

    async def get_multi(
        self, *, skip: int = 0, limit: int = 10, filter_value: str = ""
    ) -> list[LogsReadWithUserName] | None:
        """
        获取角色列表
        """

        # 1 基础查询
        condition = []
        print("收到的筛选值：", filter_value)
        # 2. 动态添加模糊查询
        if filter_value.strip():
            condition.append(
                or_(
                    # uuid 转换为字符串才能使用like
                    cast(self.model.request_id, String).like(f"%{filter_value}%")
                )
            )
        # 3. 计算总数
        count_query = select(func.count()).select_from(self.model).where(*condition)
        total = (await self.session.exec(count_query)).one()

        # 4. 分页查询, id排序
        query = (
            select(self.model)
            .options(selectinload(Logs.user))
            .where(*condition)
            .order_by(self.model.id)
            .offset(skip)
            .limit(limit)
        )
        result = (await self.session.exec(query)).all()
        return total, result  # type: ignore
